import { Component, OnInit } from '@angular/core';
import {Product} from "../../model/Product";
import {ProductService} from "../../service/product.service";
import {DialogService} from "primeng/api";
import {ProducteditComponent} from "../productedit/productedit.component";

@Component({
  selector: 'app-productadmin',
  templateUrl: './productadmin.component.html',
  styleUrls: ['./productadmin.component.css']
})
export class ProductadminComponent implements OnInit {

  pl:Array<Product>
  constructor(private productservice:ProductService
    ,private dialogService: DialogService) {
    this.pl=new Array();

  }

  ngOnInit() {
    this.loadProductList();

  }


  //从服务器端获取单页列表数据
  loadProductList(){
    this.productservice.getProductList()
      .then((data:any)=>{
        this.pl=new Array();
        this.pl=data;


      })


  }

  add(){
    //弹出编辑窗口
    const ref = this.dialogService.open(ProducteditComponent, {
      header: '添加民族产品'

    });

    //订阅窗口关闭事件

    ref.onClose.subscribe((product: Product) => {
      if (product) {
        //保存数据到服务器
        this.productservice.saveProduct(product)
          .then((data:any)=>{
            if(data.msg=='ok'){
              this.loadProductList();
            }
            else{
              //提示错误
            }


          })




      }
    });



  }

  //删除

  delete(id:string){

    this.productservice.deleteProduct(id)
      .then((data:any)=>{
        if(data.msg=='ok'){
          this.loadProductList();
        }
        else{
          //弹出错误信息;
        }


      })


  }

  update(id:string){
    //从服务器端读取数据
    this.productservice.getSingleProductById(id)
      .then((data:any)=>{
        if(data){
          let product:Product;
          product=new Product();
          product=data;

          //发送要编辑的数据到编辑窗口
          //弹出编辑窗口
          const ref = this.dialogService.open(ProducteditComponent, {
            header: '修改民族产品',
            data:{
              "product":product
            }

          });

          //订阅窗口关闭事件

          ref.onClose.subscribe((product: Product) => {
            if (product) {
              //保存数据到服务器
              this.productservice.saveProduct(product)
                .then((data:any)=>{
                  if(data.msg=='ok'){
                    this.loadProductList();
                  }
                  else{
                    //提示错误
                  }


                })




            }
          });


        }


      });




  }



}
